﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace SkypeMonitorService
{
	/// <summary>
	/// <remarks>
	/// Only for windows application, which have handle 
	/// </remarks>
	/// </summary>
	public class SessionWinApi:IDisposable
	{
		// constants that can be passed for the dwFlags parameter
		internal const int NOTIFY_FOR_THIS_SESSION = 0;
		internal const int NOTIFY_FOR_ALL_SESSIONS = 1;

		// message id to look for when processing the message (see sample code)
		internal  const int WM_WTSSESSION_CHANGE = 0x2b1;

		// WParam values that can be received: 
		const int WTS_CONSOLE_CONNECT = 0x1; // A session was connected to the console terminal.
		const int WTS_CONSOLE_DISCONNECT = 0x2; // A session was disconnected from the console terminal.
		const int WTS_REMOTE_CONNECT = 0x3; // A session was connected to the remote terminal.
		const int WTS_REMOTE_DISCONNECT = 0x4; // A session was disconnected from the remote terminal.
		const int WTS_SESSION_LOGON = 0x5; // A user has logged on to the session.
		const int WTS_SESSION_LOGOFF = 0x6; // A user has logged off the session.
		const int WTS_SESSION_LOCK = 0x7; // A session has been locked.
		const int WTS_SESSION_UNLOCK = 0x8; // A session has been unlocked.
		const int WTS_SESSION_REMOTE_CONTROL = 0x9; // A session has changed its remote controlled status

		public event EventHandler MachineLocked;
		public event EventHandler MachineUnlocked;

		[DllImport("Wtsapi32.dll",SetLastError=true)]
		[return:MarshalAs( UnmanagedType.Bool)]
		internal static extern bool WTSRegisterSessionNotification(IntPtr hWnd,uint  dwFlags);

		[DllImport("Wtsapi32.dll",SetLastError=true)]
		[return:MarshalAs( UnmanagedType.Bool)]
		internal static extern bool WTSUnRegisterSessionNotification(IntPtr hWnd);

		IntPtr Handle;

		public SessionWinApi()
        {
            if (!WTSRegisterSessionNotification(this.Handle, NOTIFY_FOR_THIS_SESSION))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
            }
        }

		~SessionWinApi()
		{
			Dispose();
		}

		//protected override void WndProc(ref Message m)
		//{
		//    if (m.Msg == WM_WTSSESSION_CHANGE)
		//    {
		//        int value = m.WParam.ToInt32();
		//        if (value == WTS_SESSION_LOCK)
		//        {
		//            OnMachineLocked(EventArgs.Empty);
		//        }
		//        else if (value == WTS_SESSION_UNLOCK)
		//        {
		//            OnMachineUnlocked(EventArgs.Empty);
		//        }
		//    }
		//    base.WndProc(ref m);
		//}



		public void Dispose()
		{
			// unregister the handle before it gets destroyed
			WTSUnRegisterSessionNotification(this.Handle);
			GC.SuppressFinalize(this);
		}
	}
}
